<template>
  <div class="multimeter-container">
    <div class="multimeter-body">
      <!-- 显示屏 -->
      <div class="display-panel" :class="{ 'backlight-on': backlightEnabled }">
        <div class="display-screen">
          <div class="display-negative-sign" v-if="showNegativeSign">-</div>
          <div class="display-value">{{ displayValue }}</div>
          <div class="display-unit">{{ currentUnit }}</div>
          <div class="display-indicators">
            <div class="indicator hold" v-if="isHoldActive">H</div>
            <div class="indicator battery" v-if="batteryLevel < 3">B</div>
          </div>
        </div>
        <div class="display-buttons">
          <div
            class="power-indicator"
            :class="{ active: isPoweredOn }"
            @click="togglePower"
          >
            POWER
          </div>
          <div
            class="hold-button"
            :class="{ active: isHoldActive }"
            @click="toggleHold"
          >
            HOLD
          </div>
          <div
            class="backlight-button"
            :class="{ active: backlightEnabled }"
            @click="toggleBacklight"
          >
            LIGHT
          </div>
        </div>
      </div>

      <!-- 档位选择区域 -->
      <div class="range-selector" v-if="isPoweredOn && currentMode !== 'off'">
        <div class="range-title">测量范围</div>
        <div class="range-options">
          <button
            v-for="range in currentRanges"
            :key="range.value"
            @click="selectRange(range.value)"
            :class="{ active: currentRange === range.value }"
          >
            {{ range.label }}
          </button>
        </div>
      </div>

      <!-- 功能旋钮 -->
      <div class="knob-container">
        <div
          class="function-knob"
          :style="{ transform: `rotate(${knobRotation}deg)` }"
          @click="showModeSelector = !showModeSelector"
        >
          <div class="knob-pointer"></div>
        </div>

        <!-- 模式选择器 -->
        <div v-if="showModeSelector" class="mode-selector">
          <button
            v-for="mode in measurementModes"
            :key="mode.value"
            @click="selectMode(mode.value)"
            :class="{ active: currentMode === mode.value }"
            :disabled="!isPoweredOn"
          >
            {{ mode.label }}
          </button>
        </div>
      </div>

      <!-- 输入端口 -->
      <div class="input-ports">
        <div
          class="port port-20a"
          @click="selectPort('20a')"
          :class="{ active: selectedPort === '20a' }"
        >
          <div class="port-label">20A</div>
          <div class="port-icon">⚡</div>
        </div>
        <div
          class="port port-mah"
          @click="selectPort('mah')"
          :class="{ active: selectedPort === 'mah' }"
        >
          <div class="port-label">mA/μA</div>
          <div class="port-icon">⚡</div>
        </div>
        <div
          class="port port-com"
          @click="selectPort('com')"
          :class="{ active: selectedPort === 'com' }"
        >
          <div class="port-label">COM</div>
          <div class="port-icon">⚡</div>
        </div>
        <div
          class="port port-voltage"
          @click="selectPort('voltage')"
          :class="{ active: selectedPort === 'voltage' }"
        >
          <div class="port-label">VΩ</div>
          <div class="port-icon">⚡</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, onUnmounted } from "vue";
import { useMultimeterStore } from "@/store/multimeterStore";

// 定义props
const props = defineProps({
  measurementValue: {
    type: String,
    default: null
  }
});

// 获取万用表store实例
const multimeterStore = useMultimeterStore();

// 响应式数据
const showModeSelector = ref(false);
const displayValue = ref("00.0");
const batteryLevel = ref(4); // 电池电量(1-5)
const showNegativeSign = ref(false);
const measurementInterval = ref(null);

// 监听props变化
watch(() => props.measurementValue, (newValue) => {
  if (newValue && !multimeterStore.getIsHoldActive && multimeterStore.getIsPoweredOn) {
    displayValue.value = newValue;
  }
});

// 计算属性
const currentUnit = computed(() => multimeterStore.getCurrentUnit);

const knobRotation = computed(() => multimeterStore.getKnobRotation);

const currentRanges = computed(() => multimeterStore.getCurrentModeRanges);

// 从store获取状态
const currentMode = computed(() => multimeterStore.getCurrentMode);
const currentRange = computed(() => multimeterStore.getCurrentRange);
const isPoweredOn = computed(() => multimeterStore.getIsPoweredOn);
const isHoldActive = computed(() => multimeterStore.getIsHoldActive);
const backlightEnabled = computed(() => multimeterStore.getBacklightEnabled);
const selectedPort = computed(() => multimeterStore.getSelectedPort);
const measurementModes = computed(() => multimeterStore.getMeasurementModes);

// 方法
const selectMode = (mode) => {
  multimeterStore.setCurrentMode(mode);
  showModeSelector.value = false;
  
  // 重置显示
  resetDisplay();
};

const selectRange = (range) => {
  multimeterStore.setCurrentRange(range);

  // 切换范围时重置显示
  if (!multimeterStore.getIsHoldActive) {
    resetDisplay();
  }
};

const selectPort = (port) => {
  multimeterStore.setSelectedPort(port);

  // 端口切换时可能影响测量
  if (!multimeterStore.getIsHoldActive) {
    resetDisplay();
  }
};

const togglePower = () => {
  multimeterStore.setIsPoweredOn(!multimeterStore.getIsPoweredOn);

  if (multimeterStore.getIsPoweredOn) {
    startMeasurement();
  } else {
    stopMeasurement();
    displayValue.value = "---";
    // 背光会在store中自动关闭
  }
};

const toggleHold = () => {
  multimeterStore.setIsHoldActive(!multimeterStore.getIsHoldActive);

  if (!multimeterStore.getIsHoldActive) {
    // 取消保持后立即更新一次测量值
    simulateSingleMeasurement();
  }
};

const toggleBacklight = () => {
  if (!multimeterStore.getIsPoweredOn) return;

  multimeterStore.setBacklightEnabled(!multimeterStore.getBacklightEnabled);

  // 背光开启一段时间后自动关闭
  if (multimeterStore.getBacklightEnabled) {
    setTimeout(() => {
      if (multimeterStore.getIsPoweredOn) {
        multimeterStore.setBacklightEnabled(false);
      }
    }, 30000); // 30秒后自动关闭背光
  }
};

const resetDisplay = () => {
  if (multimeterStore.getCurrentMode === "off" || !multimeterStore.getIsPoweredOn) {
    displayValue.value = "---";
  } else if (multimeterStore.getCurrentMode === "voltage") {
    displayValue.value = "00.0";
  } else if (multimeterStore.getCurrentMode === "resistance") {
    displayValue.value = "000";
  } else if (multimeterStore.getCurrentMode === "current") {
    displayValue.value = "0.00";
  }
};

const simulateSingleMeasurement = () => {
  if (!multimeterStore.getIsPoweredOn || multimeterStore.getCurrentMode === "off" || multimeterStore.getIsHoldActive) {
    return;
  }

  // 获取当前范围的最大值
  const rangeInfo = currentRanges.value.find(
    (r) => r.value === multimeterStore.getCurrentRange
  );
  if (!rangeInfo) return;

  let value = 0;

  // 根据不同模式生成随机测量值
  if (multimeterStore.getCurrentMode === "voltage") {
    value = Math.random() * rangeInfo.max;
    // 根据范围格式化显示
    if (multimeterStore.getCurrentRange === "200mV") {
      displayValue.value = (value * 1000).toFixed(1).padStart(5, "0");
    } else {
      const precision = rangeInfo.max >= 200 ? 0 : 1;
      displayValue.value = value.toFixed(precision).padStart(4, "0");
    }
  } else if (multimeterStore.getCurrentMode === "current") {
    value = Math.random() * rangeInfo.max;
    // 根据范围格式化显示
    if (multimeterStore.getCurrentRange === "200μA") {
      displayValue.value = (value * 1000000).toFixed(0).padStart(3, "0");
    } else if (multimeterStore.getCurrentRange === "2mA") {
      displayValue.value = (value * 1000).toFixed(3).padStart(5, "0");
    } else if (multimeterStore.getCurrentRange === "20mA") {
      displayValue.value = (value * 1000).toFixed(2).padStart(4, "0");
    } else if (multimeterStore.getCurrentRange === "200mA") {
      displayValue.value = (value * 1000).toFixed(1).padStart(4, "0");
    } else {
      displayValue.value = value.toFixed(2).padStart(4, "0");
    }
  } else if (multimeterStore.getCurrentMode === "resistance") {
    value = Math.random() * rangeInfo.max;
    // 根据范围格式化显示
    if (multimeterStore.getCurrentRange === "200Ω") {
      displayValue.value = value.toFixed(0).padStart(3, "0");
    } else if (multimeterStore.getCurrentRange === "2kΩ") {
      displayValue.value = (value / 1000).toFixed(3).padStart(5, "0");
    } else if (multimeterStore.getCurrentRange === "20kΩ") {
      displayValue.value = (value / 1000).toFixed(2).padStart(4, "0");
    } else if (multimeterStore.getCurrentRange === "200kΩ") {
      displayValue.value = (value / 1000).toFixed(1).padStart(4, "0");
    } else if (multimeterStore.getCurrentRange === "2MΩ") {
      displayValue.value = (value / 1000000).toFixed(3).padStart(5, "0");
    } else {
      displayValue.value = (value / 1000000).toFixed(2).padStart(4, "0");
    }
  }

  // 随机显示负数
  showNegativeSign.value =
    multimeterStore.getCurrentMode !== "resistance" && Math.random() > 0.7;

  // 随机闪烁小数点，模拟真实万用表的不稳定
  if (Math.random() > 0.8) {
    setTimeout(() => {
      if (!multimeterStore.getIsHoldActive) {
        displayValue.value = displayValue.value.replace(".", "");
        setTimeout(() => {
          if (!multimeterStore.getIsHoldActive) {
            simulateSingleMeasurement();
          }
        }, 100);
      }
    }, 50);
  }
};

const startMeasurement = () => {
  stopMeasurement();
  simulateSingleMeasurement();
  // 每2秒更新一次测量值
  measurementInterval.value = setInterval(() => {
    simulateSingleMeasurement();
  }, 2000);
};

const stopMeasurement = () => {
  if (measurementInterval.value) {
    clearInterval(measurementInterval.value);
    measurementInterval.value = null;
  }
};

// 生命周期钩子
onMounted(() => {
  // 只有当没有外部传入测量值且电源开启时，才开始模拟测量
  // 注意：在PTC重接线组件中，我们希望只有点击测量时才显示值，所以这里不自动开始测量
  if (!props.measurementValue && multimeterStore.getIsPoweredOn) {
    // 仅显示初始值，不启动持续测量
    displayValue.value = "00.0";
  }
});

onUnmounted(() => {
  stopMeasurement();
});

// 监听模式变化
watch(() => [multimeterStore.getCurrentMode, multimeterStore.getCurrentRange], () => {
  if (multimeterStore.getIsPoweredOn && multimeterStore.getCurrentMode !== "off" && !multimeterStore.getIsHoldActive && !props.measurementValue) {
    // 只有当没有外部传入测量值时，才模拟测量值
    displayValue.value = "00.0";
  }
});
</script>

<style scoped>
.multimeter-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f0f0f0;
  padding: 20px;
}

.multimeter-body {
  width: 320px;
  height: 550px;
  background-color: #e67e22;
  border-radius: 15px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
  position: relative;
  padding: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
  transition: all 0.3s ease;
}

/* 显示屏样式 */
.display-panel {
  background-color: #2c3e50;
  border-radius: 10px;
  padding: 15px;
  margin-bottom: 15px;
  width: 100%;
  box-sizing: border-box;
  transition: all 0.3s ease;
  border: 2px solid #34495e;
}

.display-panel.backlight-on {
  box-shadow: 0 0 20px rgba(255, 215, 0, 0.6);
  border-color: #f1c40f;
}

.display-screen {
  background-color: #27ae60;
  border-radius: 5px;
  padding: 15px;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  font-family: "Courier New", monospace;
  min-height: 70px;
  position: relative;
  overflow: hidden;
  box-shadow: inset 0 2px 5px rgba(0, 0, 0, 0.3);
}

.display-negative-sign {
  font-size: 32px;
  color: #000;
  font-weight: bold;
  margin-right: 5px;
  animation: flicker 3s infinite;
}

.display-value {
  font-size: 44px;
  font-weight: bold;
  color: #000;
  margin-right: 5px;
  letter-spacing: 1px;
  animation: flicker 5s infinite;
}

.display-unit {
  font-size: 22px;
  color: #000;
  font-weight: bold;
}

.display-indicators {
  position: absolute;
  top: 5px;
  right: 10px;
  display: flex;
  gap: 10px;
}

.indicator {
  font-size: 12px;
  font-weight: bold;
  color: #e74c3c;
  background-color: rgba(255, 255, 255, 0.8);
  padding: 2px 5px;
  border-radius: 2px;
}

.display-buttons {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
  gap: 5px;
}

.power-indicator,
.hold-button,
.backlight-button {
  flex: 1;
  padding: 6px 8px;
  border-radius: 3px;
  font-size: 11px;
  font-weight: bold;
  cursor: pointer;
  text-align: center;
  transition: all 0.2s ease;
  border: 2px solid transparent;
}

.power-indicator {
  background-color: #7f8c8d;
  color: #ecf0f1;
}

.power-indicator.active {
  background-color: #e74c3c;
  color: white;
  border-color: #c0392b;
  box-shadow: 0 0 10px rgba(231, 76, 60, 0.5);
}

.hold-button {
  background-color: #7f8c8d;
  color: #ecf0f1;
}

.hold-button.active {
  background-color: #3498db;
  color: white;
  border-color: #2980b9;
  box-shadow: 0 0 10px rgba(52, 152, 219, 0.5);
}

.backlight-button {
  background-color: #7f8c8d;
  color: #ecf0f1;
}

.backlight-button.active {
  background-color: #f1c40f;
  color: #2c3e50;
  border-color: #f39c12;
  box-shadow: 0 0 10px rgba(241, 196, 15, 0.5);
}

.power-indicator:hover,
.hold-button:hover,
.backlight-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
}

/* 档位选择器样式 */
.range-selector {
  width: 100%;
  background-color: rgba(44, 62, 80, 0.9);
  border-radius: 8px;
  padding: 10px;
  margin-bottom: 15px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
}

.range-title {
  color: #ecf0f1;
  font-size: 14px;
  font-weight: bold;
  margin-bottom: 8px;
  text-align: center;
}

.range-options {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
  justify-content: center;
}

.range-options button {
  padding: 5px 10px;
  background-color: #34495e;
  color: #ecf0f1;
  border: 1px solid #7f8c8d;
  border-radius: 4px;
  font-size: 11px;
  cursor: pointer;
  transition: all 0.2s ease;
  min-width: 60px;
}

.range-options button:hover {
  background-color: #7f8c8d;
  transform: translateY(-1px);
}

.range-options button.active {
  background-color: #27ae60;
  border-color: #229954;
  color: white;
  box-shadow: 0 0 8px rgba(39, 174, 96, 0.5);
}

/* 旋钮样式 */
.knob-container {
  position: relative;
  margin: 15px 0;
  cursor: grab;
}

.knob-container:active {
  cursor: grabbing;
}

.function-knob {
  width: 220px;
  height: 220px;
  background-color: #34495e;
  border-radius: 50%;
  position: relative;
  cursor: pointer;
  box-shadow: inset 0 5px 15px rgba(0, 0, 0, 0.5), 0 5px 15px rgba(0, 0, 0, 0.3);
  transition: transform 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 3px solid #2c3e50;
}

.function-knob:hover {
  transform: scale(1.02);
}

.function-knob::before {
  content: "";
  position: absolute;
  width: 180px;
  height: 180px;
  background-color: #2c3e50;
  border-radius: 50%;
  box-shadow: inset 0 2px 10px rgba(0, 0, 0, 0.5);
}

.knob-pointer {
  width: 6px;
  height: 90px;
  background-color: #e74c3c;
  position: absolute;
  top: 10px;
  border-radius: 3px;
  box-shadow: 0 0 10px rgba(231, 76, 60, 0.8);
  z-index: 2;
}

/* 模式选择器 */
.mode-selector {
  position: absolute;
  top: 100%;
  left: 50%;
  transform: translateX(-50%);
  background-color: #2c3e50;
  border-radius: 5px;
  padding: 10px;
  z-index: 10;
  margin-top: 10px;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
  border: 2px solid #34495e;
}

.mode-selector button {
  display: block;
  width: 100%;
  padding: 8px 15px;
  margin: 5px 0;
  background-color: #34495e;
  color: white;
  border: none;
  border-radius: 3px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 13px;
}

.mode-selector button:hover:not(:disabled) {
  background-color: #3498db;
  transform: translateX(5px);
}

.mode-selector button.active {
  background-color: #27ae60;
  box-shadow: inset 0 0 10px rgba(0, 0, 0, 0.3);
}

.mode-selector button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

/* 输入端口样式 */
.input-ports {
  display: flex;
  justify-content: space-around;
  width: 100%;
  margin: 15px 0;
}

.port {
  display: flex;
  flex-direction: column;
  align-items: center;
  cursor: pointer;
  transition: all 0.2s ease;
  padding: 5px;
  border-radius: 5px;
}

.port:hover {
  transform: scale(1.1);
  background-color: rgba(255, 255, 255, 0.1);
}

.port.active {
  background-color: rgba(255, 255, 255, 0.2);
  transform: scale(1.05);
}

.port-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 20px;
  margin-bottom: 5px;
  border: 2px solid rgba(255, 255, 255, 0.3);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
  transition: all 0.2s ease;
}

.port.active .port-icon {
  box-shadow: 0 0 15px rgba(255, 255, 255, 0.5);
  transform: scale(1.1);
}

.port-label {
  font-size: 12px;
  color: #2c3e50;
  font-weight: bold;
}

.port-20a .port-icon {
  background-color: #e74c3c;
}

.port-mah .port-icon {
  background-color: #f39c12;
}

.port-com .port-icon {
  background-color: #e74c3c;
}

.port-voltage .port-icon {
  background-color: #3498db;
}

/* 动画效果 */
@keyframes flicker {
  0%,
  100% {
    opacity: 1;
  }
  97% {
    opacity: 0.95;
  }
  98% {
    opacity: 1;
  }
  99% {
    opacity: 0.97;
  }
}

/* 响应式设计 */
@media (max-width: 480px) {
  .multimeter-body {
    width: 280px;
    height: 480px;
    padding: 15px;
  }

  .function-knob {
    width: 180px;
    height: 180px;
  }

  .function-knob::before {
    width: 150px;
    height: 150px;
  }

  .knob-pointer {
    height: 70px;
  }

  .display-value {
    font-size: 36px;
  }

  .display-negative-sign {
    font-size: 28px;
  }

  .port-icon {
    width: 35px;
    height: 35px;
  }

  .range-options button {
    min-width: 50px;
    padding: 4px 8px;
    font-size: 10px;
  }
}
</style>